package com.jiufen.Filter;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 * 解决跨域问题的拦截器,临时调试使用 暂时停止token校验
 */
//@WebFilter(urlPatterns = "/*")
@Slf4j
public class CrosFilter implements Filter {
    // 允许跨域请求的源
    private static final String ALLOWED_ORIGINS = "http://127.0.0.1:5173"; // 根据实际情况修改

    /**
     * 过滤器的主要逻辑方法
     *
     * @param servletRequest Servlet请求对象
     * @param servletResponse Servlet响应对象
     * @param filterChain 过滤链，用于将请求传递给过滤链中的下一个过滤器或目标资源
     * @throws IOException 如果在执行过程中发生I/O错误
     * @throws ServletException 如果在执行过程中发生Servlet错误
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 将Servlet请求和响应对象转换为HTTP请求和响应对象
        HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;

        try {
            log.debug("CrosFilter doFilter function is executed~");

            // 获取请求的源
            String origin = httpRequest.getHeader("Origin");
            log.debug("本次请求的源是=={}", origin);
            // 如果请求源为空，返回403错误
            if (origin == null) {
                httpResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
                return;
            }
            // 如果请求源在允许列表中，设置跨域请求头
            if (ALLOWED_ORIGINS.equals(origin)) {
                httpResponse.setHeader("Access-Control-Allow-Origin", origin);
                httpResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE,PUT");
                httpResponse.setHeader("Access-Control-Max-Age", "3600");
                httpResponse.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");

                // 如果请求方法为OPTIONS，直接返回200
                if ("OPTIONS".equalsIgnoreCase(httpRequest.getMethod())) {
                    httpResponse.setStatus(HttpServletResponse.SC_OK);
                    return;
                }
            } else {
                // 如果请求源不在允许列表中，返回403错误
                httpResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
                return;
            }

            // 继续执行过滤链中的下一个过滤器或目标资源
            filterChain.doFilter(servletRequest, servletResponse);
            log.debug("请求合法---放行~");
        } catch (Exception e) {
            // 记录错误日志并抛出Servlet异常
            log.error("Error occurred in CrosFilter: ", e);
            throw new ServletException("Error occurred in CrosFilter", e);
        }
    }
}
